using System;
using System.Collections.Generic;
using HuaRongDaoGame.Services;

namespace HuaRongDaoGame.Models
{
    /// <summary>
    /// 游戏状态枚举
    /// </summary>
    public enum GameStatus
    {
        NotStarted,     // 未开始
        Playing,        // 游戏中
        Paused,         // 暂停
        Won,           // 胜利
        Lost           // 失败
    }

    /// <summary>
    /// 游戏状态管理类
    /// </summary>
    public class GameState
    {
        /// <summary>
        /// 当前游戏状态
        /// </summary>
        public GameStatus Status { get; set; }

        /// <summary>
        /// 游戏棋盘
        /// </summary>
        public GameBoard GameBoard { get; private set; }

        /// <summary>
        /// 当前布局
        /// </summary>
        public GameLayout CurrentLayout { get; private set; }

        /// <summary>
        /// 游戏开始时间
        /// </summary>
        public DateTime StartTime { get; set; }

        /// <summary>
        /// 游戏结束时间
        /// </summary>
        public DateTime? EndTime { get; set; }

        /// <summary>
        /// 暂停开始时间
        /// </summary>
        public DateTime? PauseStartTime { get; set; }

        /// <summary>
        /// 总暂停时间
        /// </summary>
        public TimeSpan TotalPauseTime { get; set; }

        /// <summary>
        /// 当前步数
        /// </summary>
        public int MoveCount { get; set; }

        /// <summary>
        /// 最大步数限制（0表示无限制）
        /// </summary>
        public int MaxMoves { get; set; }

        /// <summary>
        /// 提示次数
        /// </summary>
        public int HintCount { get; set; }

        /// <summary>
        /// 最大提示次数
        /// </summary>
        public int MaxHints { get; set; }

        /// <summary>
        /// 游戏统计信息
        /// </summary>
        public GameStatistics Statistics { get; set; }

        /// <summary>
        /// 状态改变事件
        /// </summary>
        public event EventHandler<GameStateChangedEventArgs> StateChanged;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GameState()
        {
            Status = GameStatus.NotStarted;
            GameBoard = new GameBoard();
            Statistics = new GameStatistics();
            MaxMoves = 0; // 无限制
            MaxHints = 3;
        }

        /// <summary>
        /// 开始新游戏
        /// </summary>
        public void StartNewGame(GameLayout layout)
        {
            CurrentLayout = layout;
            GameBoard = layout.CreateGameBoard();
            StartTime = DateTime.Now;
            EndTime = null;
            PauseStartTime = null;
            TotalPauseTime = TimeSpan.Zero;
            MoveCount = 0;
            HintCount = 0;
            Status = GameStatus.Playing;

            OnStateChanged();
        }

        /// <summary>
        /// 暂停游戏
        /// </summary>
        public void PauseGame()
        {
            if (Status == GameStatus.Playing)
            {
                Status = GameStatus.Paused;
                PauseStartTime = DateTime.Now;
                OnStateChanged();
            }
        }

        /// <summary>
        /// 继续游戏
        /// </summary>
        public void ResumeGame()
        {
            if (Status == GameStatus.Paused)
            {
                Status = GameStatus.Playing;
                if (PauseStartTime.HasValue)
                {
                    TotalPauseTime += DateTime.Now - PauseStartTime.Value;
                    PauseStartTime = null;
                }
                OnStateChanged();
            }
        }

        /// <summary>
        /// 结束游戏
        /// </summary>
        public void EndGame(bool isWon)
        {
            if (Status == GameStatus.Playing || Status == GameStatus.Paused)
            {
                EndTime = DateTime.Now;
                Status = isWon ? GameStatus.Won : GameStatus.Lost;

                // 更新统计信息
                if (isWon)
                {
                    Statistics.TotalGamesWon++;
                    var completionTime = GetElapsedTime();
                    if (Statistics.BestTime == TimeSpan.Zero || completionTime < Statistics.BestTime)
                    {
                        Statistics.BestTime = completionTime;
                    }
                    if (Statistics.BestMoves == 0 || MoveCount < Statistics.BestMoves)
                    {
                        Statistics.BestMoves = MoveCount;
                    }
                }

                Statistics.TotalGamesPlayed++;
                Statistics.TotalMoves += MoveCount;
                Statistics.AverageMoves = Statistics.TotalMoves / Statistics.TotalGamesPlayed;
                Statistics.TotalTime += GetElapsedTime();

                OnStateChanged();
            }
        }

        /// <summary>
        /// 重新开始当前游戏
        /// </summary>
        public void RestartGame()
        {
            if (CurrentLayout != null)
            {
                StartNewGame(CurrentLayout);
            }
        }

        /// <summary>
        /// 从保存的数据恢复游戏状态
        /// </summary>
        public void RestoreFromSaveData(GameLayout layout, GameBoardSnapshot snapshot, int moveCount, int hintCount, DateTime startTime, TimeSpan totalPauseTime, GameStatus status)
        {
            CurrentLayout = layout;
            if (snapshot != null)
            {
                GameBoard.RestoreFromSnapshot(snapshot);
            }
            MoveCount = moveCount;
            HintCount = hintCount;
            StartTime = startTime;
            TotalPauseTime = totalPauseTime;
            Status = status;
            OnStateChanged();
        }

        /// <summary>
        /// 记录移动
        /// </summary>
        public void RecordMove()
        {
            if (Status == GameStatus.Playing)
            {
                MoveCount++;
                
                // 检查是否超过最大步数
                if (MaxMoves > 0 && MoveCount >= MaxMoves)
                {
                    EndGame(false);
                }
                // 检查是否胜利
                else if (GameBoard.IsGameWon())
                {
                    EndGame(true);
                }
                else
                {
                    OnStateChanged();
                }
            }
        }

        /// <summary>
        /// 使用提示
        /// </summary>
        public bool UseHint()
        {
            if (Status == GameStatus.Playing && HintCount < MaxHints)
            {
                HintCount++;
                OnStateChanged();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取提示
        /// </summary>
        public HintResult GetHint()
        {
            if (Status == GameStatus.Playing)
            {
                return HintService.GetNextMoveHint(GameBoard);
            }
            return null;
        }

        /// <summary>
        /// 撤销移动
        /// </summary>
        public bool UndoMove()
        {
            if (Status == GameStatus.Playing && GameBoard.UndoLastMove())
            {
                MoveCount = Math.Max(0, MoveCount - 1);
                OnStateChanged();
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取游戏进行时间
        /// </summary>
        public TimeSpan GetElapsedTime()
        {
            if (Status == GameStatus.NotStarted)
                return TimeSpan.Zero;

            var endTime = EndTime ?? DateTime.Now;
            var totalTime = endTime - StartTime;
            
            if (PauseStartTime.HasValue)
            {
                totalTime -= DateTime.Now - PauseStartTime.Value;
            }
            
            return totalTime - TotalPauseTime;
        }

        /// <summary>
        /// 获取格式化的时间字符串
        /// </summary>
        public string GetFormattedTime()
        {
            var time = GetElapsedTime();
            return string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);
        }

        /// <summary>
        /// 检查游戏是否结束
        /// </summary>
        public bool IsGameOver()
        {
            return Status == GameStatus.Won || Status == GameStatus.Lost;
        }

        /// <summary>
        /// 获取游戏状态描述
        /// </summary>
        public string GetStatusDescription()
        {
            switch (Status)
            {
                case GameStatus.NotStarted: return "未开始";
                case GameStatus.Playing: return "游戏中";
                case GameStatus.Paused: return "已暂停";
                case GameStatus.Won: return "胜利";
                case GameStatus.Lost: return "失败";
                default: return "未知";
            }
        }

        /// <summary>
        /// 触发状态改变事件
        /// </summary>
        protected virtual void OnStateChanged()
        {
            if (StateChanged != null)
            {
                StateChanged(this, new GameStateChangedEventArgs(this));
            }
        }
    }

    /// <summary>
    /// 游戏统计信息
    /// </summary>
    public class GameStatistics
    {
        /// <summary>
        /// 总游戏次数
        /// </summary>
        public int TotalGamesPlayed { get; set; }

        /// <summary>
        /// 胜利次数
        /// </summary>
        public int TotalGamesWon { get; set; }

        /// <summary>
        /// 总移动步数
        /// </summary>
        public int TotalMoves { get; set; }

        /// <summary>
        /// 平均移动步数
        /// </summary>
        public int AverageMoves { get; set; }

        /// <summary>
        /// 最佳时间
        /// </summary>
        public TimeSpan BestTime { get; set; }

        /// <summary>
        /// 最佳步数
        /// </summary>
        public int BestMoves { get; set; }

        /// <summary>
        /// 总游戏时间
        /// </summary>
        public TimeSpan TotalTime { get; set; }

        /// <summary>
        /// 胜率
        /// </summary>
        public double WinRate
        {
            get
            {
                return TotalGamesPlayed > 0 ? (double)TotalGamesWon / TotalGamesPlayed * 100 : 0;
            }
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        public GameStatistics()
        {
            TotalGamesPlayed = 0;
            TotalGamesWon = 0;
            TotalMoves = 0;
            AverageMoves = 0;
            BestTime = TimeSpan.Zero;
            BestMoves = 0;
            TotalTime = TimeSpan.Zero;
        }
    }

    /// <summary>
    /// 游戏状态改变事件参数
    /// </summary>
    public class GameStateChangedEventArgs : EventArgs
    {
        public GameState GameState { get; private set; }

        public GameStateChangedEventArgs(GameState gameState)
        {
            GameState = gameState;
        }
    }
} 